<script setup lang="ts">
import { getOrders, getOrdersList } from "@/api/marketers/orders/orders";
import { addShipping } from "@/api/marketers/shipping/shipping";
import { addDateRange } from "@/utils/ruoyi";
import type { FormInstance } from "element-plus";
import { reactive, ref, toRefs } from "vue";
import { getShippingDetail } from "../../../api/marketers/shipping/shipping";
import formattedName from "@/utils/formattedName";

interface orders {
  orderId: string;
  merchantId: number;
  addressId: number;
  userId: number;
  totalAmount: number;
  status: number;
  paymentTime: string;
  paymentMethod: number;
  createTime: string;
  pageNum: number;
  pageSize: number;
}
interface shipping {
  orderId: string;
  trackingNumber: string;
}
const dialogChat = ref(false);
const loading = ref(false);
const ordersList = ref<orders[]>([]);
const dateRange = ref();
const searchRef = ref();
const formShippingRef = ref();
const dialogVisible = ref(false);
const shipmentsVisible = ref(false);
const formRef = ref();
const total = ref(0);
const data = reactive({
  form: <orders>{},
  formShipping: <shipping>{},
  formShippingRules: {
    trackingNumber: [{ required: true, message: "必须填写物流单号", trigger: "blur" }],
  },
  queryParams: <orders>{
    pageNum: 1,
    pageSize: 10,
  },
});
const { form, queryParams, formShipping, formShippingRules } = toRefs(data);
//获取订单列表数据
async function getOrdersData() {
  loading.value = true;
  await getOrdersList(addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      console.log(response.data.rows);
      ordersList.value = response.data.rows;
      total.value = response.data.total;
    }
  );
  loading.value = false;
}

// 选择分页
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getOrdersData();
};
// 当前页
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getOrdersData();
};

//查询按钮
const selectSumbit = () => {
  queryParams.value.pageNum = 1;
  getOrdersData();
};

// 查看详情按钮
const selectDetail = async (data: orders) => {
  dialogVisible.value = true;
  await getOrders(data.orderId).then((response) => {
    form.value = response.data.data;
  });
  if (data.status !== 1 && data.status !== 0) {
    await getShippingDetail(data.orderId).then((response) => {
      formShipping.value = response.data.data;
    });
  }
};
//订单物流/发货
const shipmentsDetail = (data: orders) => {
  formShipping.value.orderId = data.orderId;
  shipmentsVisible.value = true;
};
//提交按钮
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      await addShipping(formShipping.value);
      shipmentsVisible.value = false;
      getOrdersData();
    }
  });
};
// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
import { h } from "vue";
import { ElMessageBox } from "element-plus";
import { getUserAddress } from "@/api/marketers/userAddress/userAddress";
import router from "@/router";
import { useMessage } from "@/stores/counter";
import { addUserSession } from "@/api/marketers/message/message";
//查看收货信息
const open = async (row: any) => {
  let data: any;
  await getUserAddress(row.addressId).then((response) => {
    data = response.data.data;
  });
  ElMessageBox({
    title: "收货信息",
    message: h("div", [
      h("div", "收货人姓名:" + data.receiverName),
      h("div", "手机号:" + data.receiverPhone),
      h("div", "省市区:" + data.province + data.city + data.district),
      h("div", "详细地址:" + data.tag),
    ]),
    center: true,
  });
};
getOrdersData();
//聊天
const StartChat = async (row: any) => {
  useMessage().userId = row.userId;
  await addUserSession(row.userId);
  router.push("/cs");
};
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-header style="margin: auto; max-width: 95%; height: auto">
        <el-form :inline="true" :model="queryParams" ref="searchRef" label-width="68px">
          <el-form-item prop="orderId" label="订单号">
            <el-input
              v-model="queryParams.orderId"
              style="width: 240px"
              placeholder="订单号"
            ></el-input>
          </el-form-item>

          <el-form-item prop="status" label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              style="width: 240px"
            >
              <el-option label="待支付" :value="0" />
              <el-option label="已支付/待发货" :value="1" />
              <el-option label="已发货" :value="2" />
              <el-option label="已完成" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item prop="paymentMethod" label="支付方式">
            <el-select
              v-model="queryParams.paymentMethod"
              placeholder="请选择"
              style="width: 240px"
            >
              <el-option label="现金支付" :value="0" />
              <el-option label="在线支付" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="范围时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="selectSumbit">查询</el-button>
            <el-button
              type="primary"
              @click="resetForm(searchRef), (dateRange = null), getOrdersData()"
              plain
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-header>

      <el-main class="" style="margin: auto; width: 95%">
        <el-divider />
        <el-table v-loading="loading" :data="ordersList">
          <el-table-column prop="orderId" label="订单号" />

          <el-table-column prop="totalAmount" label="订单总额">
            <template #default="scope">
              <span>¥{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <span v-if="scope.row.status == 0">待支付</span>
              <span v-if="scope.row.status == 1">已支付/待发货</span>
              <span v-if="scope.row.status == 2">已发货</span>
              <span v-if="scope.row.status == 3">已完成</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="下单时间" />
          <el-table-column prop="paymentMethod" label="支付方式">
            <template #default="scope">
              <span v-if="scope.row.paymentMethod == 0">现金支付</span>
              <span v-if="scope.row.paymentMethod == 1">在线支付</span>
            </template>
          </el-table-column>
          <el-table-column prop="paymentTime" label="支付时间" />

          <el-table-column prop="addressName" label="收货信息">
            <template #default="scope">
              <div>{{ formattedName(scope.row.addressName) }}</div>

              <el-button link plain type="primary" @click="open(scope.row)"
                >查看</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="买家Id">
            <template #default="scope">
              <div>{{ scope.row.userId }}</div>
              <el-button link type="primary" @click="StartChat(scope.row)"
                >发起聊天</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="data">
              <el-button link type="primary" @click="selectDetail(data.row)"
                >查看详情</el-button
              >
              <el-button
                link
                type="primary"
                v-if="data.row.status == 1"
                @click="shipmentsDetail(data.row)"
                >发货</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="common-footer">
        <el-affix position="bottom" :offset="40">
          <el-pagination
            style="display: flex; justify-content: center; margin-top: 20px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 15, 25]"
            size="default"
            :background="true"
            layout="sizes, prev, pager, next,jumper,total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-affix>
      </el-footer>
    </el-container>
  </div>
  <!-- 查看详情 -->
  <el-dialog
    v-model="dialogVisible"
    title="详情"
    width="500"
    @close="resetForm(formRef), resetForm(formShippingRef)"
  >
    <el-form :model="form" ref="formRef" label-width="auto" label-position="top">
      <el-row>
        <el-col :span="12">
          <el-form-item label="订单号">
            <el-input v-model="form.orderId" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="请选择状态" disabled>
              <el-option label="待支付" :value="0" />
              <el-option label="已支付/待发货" :value="1" />
              <el-option label="已发货" :value="2" />
              <el-option label="已完成" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="订单总额">
            <el-input v-model="form.totalAmount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下单时间">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              placeholder="Pick a Date"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="MMM DD, YYYY"
              time-format="HH:mm"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式">
            <el-select
              v-model="form.paymentMethod"
              placeholder="请选择"
              style="width: 240px"
              disabled
            >
              <el-option label="现金支付" :value="0" />
              <el-option label="在线支付" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付时间">
            <el-date-picker
              v-model="form.paymentTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="MMM DD, YYYY"
              time-format="HH:mm"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form
      :model="formShipping"
      ref="formShippingRef"
      :rules="formShippingRules"
      label-width="auto"
      label-position="top"
      v-if="form.status !== 0 && form.status !== 1"
    >
      <el-row>
        <el-col :span="24">
          <div style="text-align: center">
            <div
              style="
                border-bottom-style: solid;
                border-width: 1px;
                display: inline-block;
                width: 100px;
              "
            />
            物流信息
            <div
              style="
                border-bottom-style: solid;
                border-width: 1px;
                display: inline-block;
                width: 100px;
              "
            />
          </div>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="trackingNumber" label="物流单号">
            <el-input
              v-model="formShipping.trackingNumber"
              placeholder="输入物流单号"
            ></el-input
          ></el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
  <!-- 发货 -->
  <el-dialog
    v-model="shipmentsVisible"
    title="订单物流/发货"
    width="500"
    @close="resetForm(formShippingRef)"
  >
    <el-form :model="formShipping" :rules="formShippingRules" ref="formShippingRef">
      <el-form-item prop="trackingNumber" label="物流单号">
        <el-input
          v-model="formShipping.trackingNumber"
          placeholder="输入物流单号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm(formShippingRef)">发货</el-button>
        <el-button @click="shipmentsVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 客服回复 -->
  <!-- <el-dialog
    v-model="dialogChat"
    title="客服回复"
    width="800"
    @close="resetForm(formRef), resetForm(formShippingRef)"
    ><Chat
  /></el-dialog> -->
</template>
<style lang="less"></style>
